package iptables

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"regexp"
	"strconv"
	"strings"
)

func Run() {
	RunDelete()
}

func RunCreate() {
	command := "-t nat -A PREROUTING ! -i hellokitty -p tcp -m tcp --dport 8888 -j DNAT --to-destination 192.168.88.18:80"
	cmd := exec.Command("iptables", strings.Split(command, " ")...)
	preRoutingResult, err := cmd.Output()
	if err != nil {
		log.Printf("[vethbr]iptables setup DNAT Output: %v; command:%s; err: %v\n", preRoutingResult, command, err)
	} else {
		log.Println("success")
	}
}

func RunDelete() {
	hostPort := "9999"
	containerIP := "192.168.88.27"
	containerPort := "80"

	err := deletePreRouting(hostPort, containerIP, containerPort)
	if err != nil {
		fmt.Printf("Error deleting DNAT rule: %v\n", err)
	}
}

func deletePreRouting(hostPort, containerIP, containerPort string) error {
	return deleteDNATRule("PREROUTING", hostPort, containerIP, containerPort)
}

func deleteOutput(hostPort, containerIP, containerPort string) error {
	return deleteDNATRule("OUTPUT", hostPort, containerIP, containerPort)
}

// deleteDNATRule 删除指定的 DNAT 规则
// @param string link PREROUTING 或者 OUTPUT
func deleteDNATRule(link, hostPort, containerIP, containerPort string) error {
	// 获取包含行号的规则列表
	//cmd := exec.Command("iptables", "-t", "nat", "-L", "PREROUTING", "-n", "--line-numbers")
	//cmd := exec.Command("iptables", "-t", "nat", "-L", "OUTPUT", "-n", "--line-numbers")
	cmd := exec.Command("iptables", "-t", "nat", "-L", link, "-n", "--line-numbers")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return fmt.Errorf("failed to list iptables rules: %v", err)
	}

	// 定义一个正则表达式模式来匹配特定的 DNAT 规则
	pattern := fmt.Sprintf(`(\d+)\s+%s\s+(.*)\s+tcp dpt:%s to:%s:%s\s+`, link, hostPort, containerIP, containerPort)
	log.Println(pattern)
	re := regexp.MustCompile(pattern)
	/*
		num  target     prot opt source               destination
		1    DOCKER     all  --  0.0.0.0/0            0.0.0.0/0            ADDRTYPE match dst-type LOCAL
		2    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:8080 to:192.168.88.17:80
		3    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:8888 to:192.168.88.18:80
		4    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:8899 to:192.168.88.25:80
		5    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:8989 to:192.168.88.26:80
		6    DNAT       tcp  --  0.0.0.0/0            0.0.0.0/0            tcp dpt:9999 to:192.168.88.27:80
	*/
	log.Println(out.String())

	// 查找匹配的规则行号
	matches := re.FindStringSubmatch(out.String())
	if len(matches) == 0 {
		return fmt.Errorf("DNAT rule not found")
	}

	lineNumber, err := strconv.Atoi(matches[1])
	if err != nil {
		return fmt.Errorf("failed to parse line number: %v", err)
	}

	// 删除指定行号的规则
	deleteCmd := exec.Command("iptables", "-t", "nat", "-D", "PREROUTING", strconv.Itoa(lineNumber))
	err = deleteCmd.Run()
	if err != nil {
		return fmt.Errorf("failed to delete DNAT rule: %v", err)
	}

	log.Printf("Successfully deleted DNAT rule for host port %s -> container %s:%s\n", hostPort, containerIP, containerPort)
	return nil
}
